using B.S.XZYData.Api.Read.Application.Command.ProductionStatistics;
using B.S.XZYData.Domain.ZSHH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System.Linq;

namespace B.S.XZYData.Api.Read.Application.Handler.ProductionStatistics
{
    /// <summary>
    /// 查询产量统计处理器
    /// </summary>
    public class QueryProductionStatisticsHandler : IRequestHandler<QueryProductionStatisticsCommand, ApiResult<ProductionStatisticsPageResult>>
    {
        private readonly IBaseRepository<Domain.ZSHH.ProductionStatistics> _productionStatisticsRepo;
        private readonly ILogger<QueryProductionStatisticsHandler> _logger;

        public QueryProductionStatisticsHandler(
            IBaseRepository<Domain.ZSHH.ProductionStatistics> productionStatisticsRepo,
            ILogger<QueryProductionStatisticsHandler> logger)
        {
            _productionStatisticsRepo = productionStatisticsRepo;
            _logger = logger;
        }

        public async Task<ApiResult<ProductionStatisticsPageResult>> Handle(QueryProductionStatisticsCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<ProductionStatisticsPageResult>();
            try
            {
                // 构建基础查询
                var query = _productionStatisticsRepo.GetAll()
                    .Where(x => !x.IsDeleted);

                // 应用筛选条件
                query = ApplyFilters(query, request);

                // 应用排序
                query = ApplySorting(query, request.SortField, request.SortDirection);

                // 获取总数
                var totalCount = await query.CountAsync();

                // 分页查询
                var productionStatisticsList = await query
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync();

                // 转换为DTO
                var productionStatisticsDtoList = productionStatisticsList.Select(item => new ProductionStatisticsDto
                {
                    Id = item.Id,
                    ReportingDate = item.ReportingDate,
                    WorkOrderPlanCount = item.WorkOrderPlanCount,
                    ProductName = item.ProductName,
                    ProductNumber = item.ProductNumber,
                    ProductSpecification = item.ProductSpecification,
                    Unit = item.Unit,
                    Quantity = item.Quantity,
                    CreatorDate = item.CreatorDate,
                    Creator = item.Creator
                }).ToList();

                var pageResult = new ProductionStatisticsPageResult
                {
                    Data = productionStatisticsDtoList,
                    Total = totalCount,
                    PageIndex = request.PageIndex,
                    PageSize = request.PageSize
                };

                res.Data = pageResult;
                res.Code = ApiEnum.Success;
                res.Msg = "查询成功";

                return await System.Threading.Tasks.Task.FromResult(res);
            }
            catch (Exception ex)
            {
                _logger.LogError($"查询产量统计异常：{ex.Message}");
                res.Msg = "查询产量统计异常：" + ex.Message;
                res.Code = ApiEnum.Error;
                return await System.Threading.Tasks.Task.FromResult(res);
            }
        }

        /// <summary>
        /// 应用筛选条件
        /// </summary>
        private ISugarQueryable<Domain.ZSHH.ProductionStatistics> ApplyFilters(
            ISugarQueryable<Domain.ZSHH.ProductionStatistics> query,
            QueryProductionStatisticsCommand request)
        {
            // 报工日期范围筛选
            if (request.ReportingDateStart.HasValue)
            {
                query = query.Where(x => x.ReportingDate >= request.ReportingDateStart.Value);
            }
            if (request.ReportingDateEnd.HasValue)
            {
                query = query.Where(x => x.ReportingDate <= request.ReportingDateEnd.Value);
            }

            // 工单计划数范围筛选
            if (request.WorkOrderPlanCountMin.HasValue)
            {
                query = query.Where(x => x.WorkOrderPlanCount >= request.WorkOrderPlanCountMin.Value);
            }
            if (request.WorkOrderPlanCountMax!=0)
            {
                query = query.Where(x => x.WorkOrderPlanCount <= request.WorkOrderPlanCountMax.Value);
            }

            // 产品名称筛选
            if (!string.IsNullOrEmpty(request.ProductName))
            {
                query = query.Where(x => x.ProductName.Contains(request.ProductName));
            }

            // 产品编号筛选
            if (!string.IsNullOrEmpty(request.ProductNumber))
            {
                query = query.Where(x => x.ProductNumber.Contains(request.ProductNumber));
            }

            // 产品规格筛选
            if (!string.IsNullOrEmpty(request.ProductSpecification))
            {
                query = query.Where(x => x.ProductSpecification.Contains(request.ProductSpecification));
            }

            // 单位筛选
            if (!string.IsNullOrEmpty(request.Unit))
            {
                query = query.Where(x => x.Unit.Contains(request.Unit));
            }

            // 数量范围筛选
            if (request.QuantityMin.HasValue)
            {
                query = query.Where(x => x.Quantity >= request.QuantityMin.Value);
            }
            if (request.QuantityMax!=0)
            {
                query = query.Where(x => x.Quantity <= request.QuantityMax.Value);
            }

            return query;
        }

        /// <summary>
        /// 应用排序
        /// </summary>
        private ISugarQueryable<Domain.ZSHH.ProductionStatistics> ApplySorting(
            ISugarQueryable<Domain.ZSHH.ProductionStatistics> query,
            string sortField,
            string sortDirection)
        {
            switch (sortField.ToLower())
            {
                case "reportingdate":
                    return sortDirection.ToLower() == "asc"
                        ? query.OrderBy(x => x.ReportingDate)
                        : query.OrderByDescending(x => x.ReportingDate);

                case "workorderplancount":
                    return sortDirection.ToLower() == "asc"
                        ? query.OrderBy(x => x.WorkOrderPlanCount)
                        : query.OrderByDescending(x => x.WorkOrderPlanCount);

                default:
                    // 默认按Id倒序
                    return query.OrderByDescending(x => x.Id);
            }
        }
    }
} 